/*
 * SoyWindowClass.cpp
 *
 *  Created on: 2012-10-20
 *      Author: yangentao@gmail.com
 */

#include "SoyWindowClass.h"

const LPCTSTR soyWindowClassName = TEXT("__soyWindowClassName__");
const LPCTSTR soyWindowClassNameWithoutDoubleClick = TEXT("__soyWindowClassNameWithoutDoubleClick__");

LPCTSTR getSoyWindowClassName(bool withDoubleClick) {
	return withDoubleClick ? soyWindowClassName : soyWindowClassNameWithoutDoubleClick;
}

WindowClass* soyClass = 0;
WindowClass* soyClassNoDBClick = 0;
void registerSoyWindowClass() {
	if (!soyClass) {
		soyClass = new WindowClass;
		soyClass->classEx.style |= CS_DBLCLKS;
		soyClass->createClass(soyWindowClassName);
		soyClass->registerClass();
	}
	if (!soyClassNoDBClick) {
		soyClassNoDBClick = new WindowClass;
		soyClassNoDBClick->classEx.style &= ~CS_DBLCLKS;
		soyClassNoDBClick->createClass(soyWindowClassNameWithoutDoubleClick);
		soyClassNoDBClick->registerClass();
	}
}
void unregisterSoyWindowClass() {
	if (soyClass) {
		soyClass->unregisterClass();
		delete soyClass;
		soyClass = 0;
	}
	if (soyClassNoDBClick) {
		soyClassNoDBClick->unregisterClass();
		delete soyClassNoDBClick;
		soyClassNoDBClick = 0;
	}
}

WindowClass::WindowClass() {
	atom = 0;
	memset(&classEx, 0, sizeof(WNDCLASSEX));
	classEx.cbSize = sizeof(WNDCLASSEX);
	classEx.style = CS_HREDRAW | CS_VREDRAW;
	classEx.cbClsExtra = 0;
	classEx.cbWndExtra = sizeof(void*);
	classEx.hInstance = GetModuleHandle(0);
	classEx.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
	classEx.hCursor = LoadCursor(0, IDC_ARROW );
	classEx.lpszMenuName = 0;
}
WindowClass::~WindowClass() {
}
LRESULT CALLBACK XWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void WindowClass::createClass(LPCTSTR className) {
	classEx.lpszClassName = className;
	classEx.lpfnWndProc = &XWndProc;
}
void WindowClass::createClass(LPCTSTR className, WNDPROC wndPRoc) {
	classEx.lpszClassName = className;
	classEx.lpfnWndProc = wndPRoc;
}
void WindowClass::createClass(LPCTSTR className, WNDPROC wndPRoc, UINT iconResID, UINT iconSmallResID, UINT menuResID) {
	classEx.lpszClassName = className;
	classEx.lpfnWndProc = wndPRoc;
	classEx.hIcon = iconResID == 0 ? 0 : LoadIcon(GetModuleHandle(0), MAKEINTRESOURCE(iconResID) );
	classEx.hIconSm = iconSmallResID == 0 ? 0 : LoadIcon(GetModuleHandle(0), MAKEINTRESOURCE(iconSmallResID) );
	classEx.lpszMenuName = menuResID == 0 ? 0 : MAKEINTRESOURCE(menuResID);
}
bool WindowClass::registerClass() {
	if (!atom) {
		atom = RegisterClassEx(&classEx);
	}
	return atom != 0;
}
void WindowClass::unregisterClass() {
	if (atom) {
		UnregisterClass(classEx.lpszClassName, classEx.hInstance);
	}
}
bool WindowClass::isRegistered() {
	return atom != 0;
}
